package com.thiswhyme.mail.service;

import com.thiswhyme.common.utils.json.fastjson.FastJsonUtils;
import com.thiswhyme.mail.config.EmailProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.time.LocalDateTime;

/**
 * @description: 异常通知邮件发送器
 * @author: thiswhyme
 * @date: 2021/5/6
 */
@Slf4j
@Service
public class ExceptionEmailSender extends AbstractEmailSender {

    @Value("${spring.profiles.active:DEV}")
    private String serverEnv;

    @Autowired
    private JavaMailSender mailSender;

    @Override
    public void send(EmailProperties.EmailProperty property, String detail, String bizParam) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeHelper = new MimeMessageHelper(message, true);
            property = getAndCheckEmailProperty(property, this.getClass().getSimpleName());

            String serverEnvStr = "【" + serverEnv + "环境】";
            mimeHelper.setFrom(property.getFrom());
            mimeHelper.setTo(property.getTo().toArray(new String[property.getTo().size()]));
            mimeHelper.setSubject(serverEnvStr + String.format(property.getSubject(), bizParam));
            mimeHelper.setText(generateContent(detail), true);
            mimeHelper.setCc(property.getCc().toArray(new String[property.getCc().size()]));
            mailSender.send(message);
            log.info("邮件发送成功, property：{}, detail：{}", FastJsonUtils.obj2String(property), detail);
        } catch (MailException | MessagingException e) {
            log.error("邮件发送失败, property：{}, detail：{}", FastJsonUtils.obj2String(property), detail, e);
        }
    }

    /**
     * 组装邮件内容
     * @param detail
     * @return
     */
    private String generateContent(String detail) {
        StringBuffer content = new StringBuffer()
                .append("<html>\n")
                .append("<body>\n")
                .append("<ul>\n")
                .append("<li><h4>详细信息：</h4></li>")
                .append("【" + LocalDateTime.now() + "】" + detail)
                .append("</ul>\n")
                .append("</body>\n")
                .append("</html>");
        return content.toString();
    }
}
